package com.my.aop;

import com.my.bean.User;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author: marshal
 * @date: 2021-11-02 11:43 AM
 */
@Aspect
@Component
@Slf4j
public class UserAspect extends CommonPoints {

    /**
     *  通过切面获取返回参数
     *
     * @param joinPoint
     * @param result
     * @throws Throwable
     */
    @AfterReturning(returning = "result", pointcut = "userAnnotation()")
    public void doAfterReturning(JoinPoint joinPoint, Object result) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 处理完请求，返回内容
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
        //将返回值转换成user对象
        User user = (User) result;
        // user => User(super=BaseBean(id=3, deleted=null, createTime=Fri Nov 26 11:49:23 CST 2021, updateTime=Fri Nov 26 11:49:23 CST 2021), name=Rose, age=14)
        log.info("user => {}", user);
    }
}
